home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 49 / Amiga Format CD49 (2000-01-17)(Future Publishing)(GB)(Track 1 of 3)[!][issue 2000-02].iso / -serious- / misc / mmulib / c_sources / mufastzero.c < prev    next >
C/C++ Source or Header  |  1999-11-29  |  39KB  |  1,059 lines

  1. /*****************************************************************
  2.  ** MuFastZero                                                  **
  3.  **                                                             **
  4.  ** A MMU library compatible zeropage remapper                  **
  5.  ** Version 1.10 29.08.1999 © THOR-Software, by Thomas Richter  **
  6.  *****************************************************************/
  7.  
  8. /// Includes
  9. #include <exec/types.h>
  10. #include <exec/memory.h>
  11. #include <exec/ports.h>
  12. #include <exec/execbase.h>
  13. #include <dos/dos.h>
  14. #include <mmu/mmubase.h>
  15. #include <mmu/context.h>
  16. #include <mmu/mmutags.h>
  17. #include <workbench/startup.h>
  18.  
  19. #include <proto/exec.h>
  20. #include <proto/mmu.h>
  21. #include <proto/dos.h>
  22. #include <proto/icon.h>
  23.  
  24. #include <string.h>
  25. ///
  26. /// Defines
  27. #define STRINGDATE "29.8.99"
  28. #define STRINGVERSION "40.10"
  29. #define CACHEFLAGS (MAPP_CACHEINHIBIT|MAPP_COPYBACK|MAPP_NONSERIALIZED|MAPP_IMPRECISE)
  30.  
  31. #define TEMPLATE "ON=FASTZERO/S,OFF=NOFASTZERO/S,FASTEXEC/S,FORCENATIVE/S,MOVESSP=FASTSSP/S,STACKSIZE/K/N"
  32.  
  33. #define OPT_ON  0
  34. #define OPT_OFF 1
  35. #define OPT_FASTEXEC 2
  36. #define OPT_FORCENATIVE 3
  37. #define OPT_FASTSSP 4
  38. #define OPT_STACKSIZE 5
  39. #define OPT_WINDOW 6
  40. #define OPT_COUNT 7
  41. ///
  42. /// Statics
  43. struct MMUBase *MMUBase;
  44. struct DosLibrary *DOSBase;
  45. struct ExecBase *SysBase;
  46. struct Library *IconBase;
  47.  
  48. void *_cw_to;
  49. void *_cw_from;
  50. ULONG _cw_size;
  51. ///
  52. /// Protos
  53. int __asm __saveds main(void);
  54. int BuildFastZero(LONG fastexec);
  55. int RemoveFastZero(void);
  56. ULONG ChipLowEnd(void);
  57. int KillFastZero(void);
  58. struct RDArgs *ReadTTArgs(struct WBStartup *msg,LONG args[],struct RDArgs **tmp);
  59. BOOL SetPages(struct MMUContext *ctx,ULONG props,ULONG lower,ULONG size,ULONG pagesize,ULONG dest);
  60. void CopyMMULess(void *to,void *from,ULONG size);
  61. ULONG __CopyWO();
  62. int MoveSSP(LONG size);
  63. void SuperStackSwap(UBYTE *newstack,ULONG size);
  64. ///
  65. /// Strukturen
  66. struct FastZeroPort {
  67.         struct MsgPort          frp_Port;
  68.         UWORD                   frp_cludgefill;
  69.         void                   *frp_Logical;            /* Logical position this is remapped to */
  70.         void                   *frp_Physical;           /* Physical location of the RAM used for remapping */
  71.         ULONG                   frp_Lower;              /* where remapping was started */
  72.         ULONG                   frp_Size;               /* size of the allocated memory */
  73.         struct Library         *frp_Base;               /* Keep the library open */
  74.         struct MemHeader       *frp_LowMemHeader;
  75.         ULONG                   frp_CacheFlags;         /* Keeps the caching mode for the remapping destination */
  76.         char                    frp_Name[32];           /* keeps the name of the port */
  77. };
  78.  
  79. /* This is the port build by MuMove4k */
  80.  
  81. struct MuMove4KPort {
  82.         struct MsgPort          mrp_Port;
  83.         UWORD                   mrp_cludgefill;
  84.         void                   *mrp_private;
  85.         struct MemHeader       *mrp_LowMemHeader;
  86.         ULONG                   mrp_UpperEnd;
  87. };
  88. ///
  89.  
  90. char version[]="$VER: MuFastZero " STRINGVERSION " (" STRINGDATE ") © THOR";
  91.  
  92. /// main
  93. int __asm __saveds main(void)
  94. {
  95. LONG args[OPT_COUNT];
  96. struct RDArgs *rd,*myrd;
  97. struct Process *proc;
  98. int rc=20;
  99. LONG err;
  100. struct WBStartup *msg;
  101. BPTR oldout;
  102. struct MsgPort *oldconsole;
  103. LONG stack;
  104.  
  105.  
  106.         SysBase=*((struct ExecBase **)(4L));
  107.  
  108.         memset(args,0,sizeof(LONG)*OPT_COUNT);
  109.         /* Wait for the workbench startup, if any */
  110.         proc=(struct Process *)FindTask(NULL);
  111.  
  112.         if (!(proc->pr_CLI)) {
  113.                 WaitPort(&(proc->pr_MsgPort));
  114.                 msg=(struct WBStartup *)GetMsg(&(proc->pr_MsgPort));
  115.         } else  msg=NULL;
  116.  
  117.         if (DOSBase=(struct DosLibrary *)OpenLibrary("dos.library",37L)) {
  118.                 if (MMUBase=(struct MMUBase *)OpenLibrary("mmu.library",0L)) {
  119.  
  120.                         myrd=NULL;      /* reset the temporary ReadArgs */
  121.                         oldout=NULL;
  122.                         oldconsole=NULL;
  123.                         if (msg) {
  124.                                 oldout=SelectOutput(NULL);
  125.                                 oldconsole=SetConsoleTask(NULL);
  126.                                 rd=ReadTTArgs(msg,args,&myrd);
  127.                         } else  rd=ReadArgs(TEMPLATE,args,NULL);
  128.  
  129.                         if (rd) {
  130.                                 if (!GetMMUType()) {
  131.                                         Printf("MuFastZero requires a working MMU.\n");
  132.                                         err=10;
  133.                                 } else {
  134.                                         /* Argument parser worked, call main routine */
  135.                                         err=0;
  136.  
  137.                                         if (args[OPT_FORCENATIVE])
  138.                                                 err=KillFastZero();
  139.  
  140.                                         if (err<10 && ((args[OPT_ON]) || ((!args[OPT_OFF]) && (!args[OPT_FASTSSP]))))
  141.                                                         err=BuildFastZero(args[OPT_FASTEXEC]);
  142.  
  143.                                         if (err<10 && args[OPT_OFF])
  144.                                                 err=RemoveFastZero();
  145.  
  146.                                         if (err<10 && args[OPT_FASTSSP]) {
  147.                                                 if (args[OPT_STACKSIZE]) {
  148.                                                         stack=*(LONG *)args[OPT_STACKSIZE];
  149.                                                 } else  stack=0;
  150.                                                 err=MoveSSP(stack);
  151.                                         }
  152.                                 }
  153.  
  154.                                 FreeArgs(rd);
  155.                                 if (myrd) FreeDosObject(DOS_RDARGS,myrd);
  156.                                 if (msg)  Close(SelectOutput(NULL));
  157.                         } else  err=IoErr();
  158.  
  159.                         if (msg) {
  160.                                 SelectOutput(oldout);
  161.                                 SetConsoleTask(oldconsole);
  162.                         }
  163.  
  164.                         if (err<64) {
  165.                                 rc=err;
  166.                                 err=0;
  167.                         } else {
  168.                                 if (!msg) PrintFault(err,"MuFastZero failed");
  169.                                 rc=10;
  170.                         }
  171.                         SetIoErr(err);
  172.  
  173.                         CloseLibrary((struct Library *)MMUBase);
  174.                 } else PrintFault(ERROR_OBJECT_NOT_FOUND,"MuFastZero requires the mmu.library");
  175.                 CloseLibrary((struct Library *)DOSBase);
  176.         }
  177.  
  178.         return rc;
  179. }
  180. ///
  181. /// ReadTTArgs
  182. struct RDArgs *ReadTTArgs(struct WBStartup *msg,LONG args[],struct RDArgs **tmp)
  183. {
  184. struct WBArg *wbarg;
  185. struct DiskObject *dop;
  186. char **tt;                      /* ToolTypes array */
  187. char *wbstr;                    /* Our self-made workbench argument string */
  188. char *here;
  189. BPTR oldlock;
  190. ULONG len;
  191. struct RDArgs *rd=NULL,*myrd=NULL;
  192. LONG err=0;
  193. BPTR newout;
  194.  
  195.         if (IconBase=OpenLibrary("icon.library",37L)) {
  196.                 if (wbarg=msg->sm_ArgList) {
  197.                         /* use a project icon if there is one... */
  198.                         if (msg->sm_NumArgs > 1) wbarg++;
  199.  
  200.                         /* go into the directory */
  201.                         oldlock=CurrentDir(wbarg->wa_Lock);
  202.  
  203.                         if (dop=GetDiskObject(wbarg->wa_Name)) {
  204.                                 if (tt=dop->do_ToolTypes) {
  205.                                         /* Read a special tool type for the output window */
  206.  
  207.                                         /* Calc the size of the argument string */
  208.  
  209.                                         len = 3;        /* reserve space for SPC,LF,NUL */
  210.                                         while (*tt) {
  211.                                                 len += strlen(*tt)+1;   /* string, plus space */
  212.                                                 tt++;
  213.                                         }
  214.  
  215.                                         if (wbstr=AllocVec(len,MEMF_PUBLIC)) {
  216.                                                 /* Now copy the arguments into this string, one by one
  217.                                                    and check whether the argument string is still valid. */
  218.  
  219.                                                 tt=dop->do_ToolTypes;
  220.                                                 here=wbstr;
  221.                                                 do{
  222.                                                         *here='\0';                     /* terminate string */
  223.                                                         /* Check whether this tool type is
  224.                                                            commented out. Just ignore it in this case */
  225.                                                         if (*tt) {
  226.                                                                 if (**tt=='(' || **tt==';')
  227.                                                                         continue;
  228.  
  229.                                                                 strcpy(here,*tt);      /* Add TT string */
  230.                                                         }
  231.                                                         len=strlen(here);
  232.                                                         here[len]='\n';
  233.                                                         here[len+1]='\0';               /* terminate string */
  234.  
  235.                                                         /* Now try to ReadArg' this string */
  236.  
  237.                                                         /* release old arguments left over from last loop */
  238.                                                         if (rd) FreeArgs(rd);
  239.                                                         if (myrd) FreeDosObject(DOS_RDARGS,myrd);
  240.                                                         rd=NULL;
  241.                                                         memset(args,0,sizeof(LONG)*OPT_COUNT);
  242.  
  243.                                                         if (myrd=AllocDosObject(DOS_RDARGS,NULL)) {
  244.                                                                 /* Allocate and setup the ReadArgs source */
  245.                                                                 myrd->RDA_Source.CS_Buffer=wbstr;
  246.                                                                 myrd->RDA_Source.CS_Length=strlen(wbstr);
  247.  
  248.                                                                 if (rd=ReadArgs(TEMPLATE ",WINDOW/K",args,myrd)) {
  249.                                                                         /* Is this still valid? */
  250.                                                                         here[len]=' ';
  251.                                                                         here+=len+1;
  252.                                                                         /* if so, accept this argument and go on */
  253.                                                                 } else {
  254.                                                                         err=IoErr();
  255.                                                                         if (err==ERROR_NO_FREE_STORE) break;
  256.                                                                         else    err=0;  /* Ignore unknown or invalid arguments silently */
  257.                                                                 }
  258.                                                         } else {
  259.                                                                 err=ERROR_NO_FREE_STORE;
  260.                                                                 break;
  261.                                                         }
  262.                                                 }while(*tt++);
  263.  
  264.                                                 FreeVec(wbstr);
  265.                                         } else err=ERROR_NO_FREE_STORE;
  266.                                 } else err=ERROR_REQUIRED_ARG_MISSING; /* Huh, how should this happen ? */
  267.                                 FreeDiskObject(dop);
  268.                         } else err=IoErr();
  269.                         CurrentDir(oldlock);
  270.                 } else err=ERROR_REQUIRED_ARG_MISSING; /* This should not happen either */
  271.                 CloseLibrary(IconBase);
  272.         } else err=ERROR_OBJECT_NOT_FOUND;    /* This should not happen */
  273.  
  274.         /* Open an output stream */
  275.  
  276.         if (err==0) {
  277.                 if (newout=Open((args[OPT_WINDOW])?((char *)args[OPT_WINDOW]):("NIL:"),MODE_NEWFILE)) {
  278.                         SelectOutput(newout);
  279.                         /* Hack in the output console. Well, well... */
  280.                         SetConsoleTask(((struct FileHandle *)(BADDR(newout)))->fh_Type);
  281.                 } else err=IoErr();
  282.         }
  283.  
  284.         if (err) {
  285.                 if (rd)   FreeArgs(rd);
  286.                 if (myrd) FreeDosObject(DOS_RDARGS,myrd);
  287.                 SetIoErr(err);
  288.                 rd=NULL;
  289.                 myrd=NULL;
  290.         }
  291.  
  292.         *tmp=myrd;
  293.         return rd;
  294. }
  295. ///
  296. /// SetPages
  297. BOOL SetPages(struct MMUContext *ctx,ULONG props,ULONG lower,ULONG size,ULONG pagesize,ULONG dest)
  298. {
  299. ULONG pages,i;
  300. ULONG base;
  301.  
  302.         pages=size/pagesize;
  303.         base=0;
  304.         for(i=0;i<pages;i++) {
  305.                 if (!SetPageProperties(ctx,props,~0L,lower+base,MAPTAG_DESTINATION,dest+base,TAG_DONE))
  306.                         return FALSE;
  307.                 base+=pagesize;
  308.         }
  309.  
  310.         return TRUE;
  311. }
  312. ///
  313. /// BuildFastZero
  314. int BuildFastZero(LONG fastexec)
  315. {
  316. void *mem=NULL,*pmem=NULL;
  317. ULONG pagesize,size,psize,align;
  318. ULONG lower;
  319. struct FastZeroPort *port;
  320. struct MuMove4KPort *mport;
  321. struct MMUContext *ctx,*sctx;   /* default context, supervisorcontext */
  322. struct MinList *ctxl,*sctxl;    /* Copies of the mappings currently active */
  323. int err=ERROR_NO_FREE_STORE;
  324. ULONG props,cacheflags;
  325. BOOL retry;
  326.  
  327.  
  328.         Forbid();                               /* Shut up PatchWork */
  329.  
  330.         /* If this is already installed, warn and return. */
  331.  
  332.         if (FindPort("« MuFastZero »")) {
  333.                 Permit();
  334.                 Printf("MuFastZero already running.\n");
  335.                 return 5;
  336.         }
  337.  
  338.         Permit();
  339.  
  340.         ctx=DefaultContext();   /* get the default context */
  341.         sctx=SuperContext(ctx); /* get the supervisor context for this one */
  342.  
  343.         /* Read the size */
  344.         pagesize=GetPageSize(ctx);
  345.  
  346.         if (GetPageSize(sctx)!=pagesize) {
  347.                 Printf("Supervisor and user page size are different,\n"
  348.                        "MuFastZero can't be installed.\n");
  349.                 return 10;
  350.         }
  351.  
  352.         size=pagesize;
  353.         if (size>ChipLowEnd()) {
  354.                 size=0;
  355.         }
  356.         align=RemapSize(ctx);
  357.  
  358.         if (fastexec) {
  359.                 Forbid();
  360.                 mport=(struct MuMove4KPort *)FindPort("« MuMove4K »");
  361.                 if (mport) {
  362.                         size=mport->mrp_UpperEnd;
  363.                 }
  364.                 Permit();
  365.                 if (mport==NULL) {
  366.                         Printf("MuMove4K is not installed, can't remap ExecBase.\n");
  367.                         return 10;
  368.                 }
  369.         } else mport=NULL;
  370.  
  371.         if (size==0) {
  372.                 Printf("The MMU page size is too large for MuFastZero.\n");
  373.                 return 10;
  374.         }
  375.  
  376.         port=AllocMem(sizeof(struct FastZeroPort),MEMF_CLEAR|MEMF_PUBLIC);
  377.         if (port) {
  378.  
  379.          /* Lock the context, make sure nobody is messing with the memory */
  380.          LockContextList();      /* We've to lock the list first, we want to lock more than one */
  381.          LockMMUContext(ctx);
  382.          LockMMUContext(sctx);
  383.          err=0;
  384.  
  385.          /* Read the properties of the zeropage. If this is either invalid
  386.             or already remapped, don't touch. */
  387.  
  388.          lower=0;
  389.  
  390.          do {
  391.  
  392.                 retry=FALSE;
  393.                 props=GetPageProperties(ctx,lower,TAG_DONE);
  394.                 props|=GetPageProperties(sctx,lower,TAG_DONE);
  395.  
  396.                 if ((props & MAPP_INVALID) || (props & MAPP_SWAPPED) ||
  397.                     (props & MAPP_SUPERVISORONLY)) {
  398.  
  399.                         if (fastexec && (size>pagesize)) {
  400.                                 size-=pagesize;
  401.                                 lower+=pagesize;
  402.                                 retry=TRUE;
  403.                         } else {
  404.                                 Printf("The zero page is invalidated and can't be remapped.\n");
  405.                                 err=10;
  406.                         }
  407.                 }
  408.          } while(retry);
  409.  
  410.          if ((props & MAPP_REMAPPED) && (err==0)) {
  411.                 Printf("The zero page is already remapped.\n");
  412.                 err=10;
  413.          }
  414.  
  415.          if (err==0L) {
  416.  
  417.           /* We request FAST here, explicitly. Taking chip memory for the
  418.              image doesn't make sense, this isn't fast either... */
  419.  
  420.           mem=AllocAligned(size+lower,MEMF_PUBLIC|MEMF_FAST|MEMF_CLEAR,align);
  421.           if (mem) {
  422.            psize=size+lower;
  423.            pmem=mem;
  424.            PhysicalLocation(ctx,&pmem,&psize);
  425.            if (psize!=size+lower) {
  426.                 Printf("The allocated memory is fragmentated, unsupported by MuFastZero.\n");
  427.                 err=10;
  428.            }
  429.           } else err=ERROR_NO_FREE_STORE;
  430.          }
  431.  
  432.          if (err==0L) {
  433.  
  434.             cacheflags=GetProperties(ctx,(ULONG)mem,TAG_DONE) & CACHEFLAGS;
  435.  
  436.             /* Make a copy of the software levels to be able to restore
  437.                them later in case of an error. */
  438.  
  439.             if (ctxl=GetMapping(ctx)) {
  440.              if (sctxl=GetMapping(sctx)) {
  441.  
  442.               /* Modify both contexts such that the zeropage is SINGLE.
  443.                  This operation is very costy, but it doesn't matter
  444.                  except for speed penalties if this is not un-done */
  445.  
  446.               err=ERROR_NO_FREE_STORE;
  447.               props=MAPP_SINGLEPAGE;
  448.  
  449.               if (SetProperties(ctx,props,props,lower,size,TAG_DONE)) {
  450.                if (RebuildTree(ctx)) {
  451.                 if (SetProperties(sctx,props,props,lower,size,TAG_DONE)) {
  452.                  if (RebuildTree(sctx)) {
  453.  
  454.                   /* Copy the zeropage over */
  455.                   Disable();
  456.  
  457.                   /* Fill in SysBase at location 4 */
  458.                   ((ULONG *)mem)[1]=(ULONG)SysBase;
  459.                   memcpy((char *)mem+lower,(char *)lower,(size_t)size);
  460.  
  461.                   /* The new property flags, or in the cache flags */
  462.                   props=MAPP_REMAPPED|MAPP_SINGLEPAGE|cacheflags;
  463.                   CacheClearU();
  464.  
  465.                   /* Map in the properties immediately. This should always work,
  466.                      except the parameters are invalid - which they aren't.
  467.                      This extra step is required because all other calls might
  468.                      break the Disable() above. */
  469.                   if (SetPages(ctx,props,lower,size,pagesize,(ULONG)pmem+lower)) {
  470.                    if (SetPages(sctx,props,lower,size,pagesize,(ULONG)pmem+lower)) {
  471.  
  472.                     /* Tell the contexts to relocate the zero page even in case MuForce
  473.                        is installed later, i.e. the software emulation should read
  474.                        the data from the relocated position, not from the original. */
  475.  
  476.                     SetMMUContextData(ctx,MCXTAG_ZEROBASE,pmem,TAG_DONE);
  477.                     SetMMUContextData(sctx,MCXTAG_ZEROBASE,pmem,TAG_DONE);
  478.  
  479.                     /* Now make the modifications in the abstraction level. */
  480.                     if (SetProperties(ctx,props,~0L,lower,size,MAPTAG_DESTINATION,(ULONG)pmem+lower,TAG_DONE)) {
  481.                      if (SetProperties(sctx,props,~0L,lower,size,MAPTAG_DESTINATION,(ULONG)pmem+lower,TAG_DONE)) {
  482.  
  483.                         /* The modifications in the hardware level are actually already done.
  484.                            Calling RebuildTree isn't stricly required here, but we do it
  485.                            anyways to clear the dirty flags. This might or might not fail,
  486.                            but the resulting MMU trees are always what we want. In
  487.                            case it fails, the dirty flags are set. So what... */
  488.  
  489.                         /* The RebuildTree's are below... */
  490.  
  491.                         /* Everything worked fine so far.... */
  492.                         port->frp_Port.mp_Node.ln_Type=NT_MSGPORT;
  493.                         port->frp_Port.mp_Node.ln_Name=port->frp_Name;
  494.                         strcpy(port->frp_Name,"« MuFastZero »");
  495.                         port->frp_Port.mp_Flags=PA_IGNORE;
  496.                         NewList(&(port->frp_Port.mp_MsgList));
  497.  
  498.                         port->frp_Physical=pmem;
  499.                         port->frp_Logical=mem;
  500.                         port->frp_Size=size;
  501.                         port->frp_Lower=lower;
  502.                         port->frp_CacheFlags=cacheflags;
  503.                         if (mport) {
  504.                                 port->frp_LowMemHeader=mport->mrp_LowMemHeader;
  505.                                 port->frp_LowMemHeader->mh_Attributes=0x0000;   /* remove the chip attribute */
  506.                         }
  507.  
  508.                         port->frp_Base=OpenLibrary("mmu.library",0L);
  509.                         AddPort(&(port->frp_Port));
  510.  
  511.  
  512.                         /* We're done here. Fine. */
  513.                         err=0;
  514.                         mem=NULL;
  515.                         port=NULL;
  516.  
  517.                      }
  518.                     }
  519.  
  520.                    /* We can't set the software level. Urgh. At least, we can
  521.                       restore it how it looked like before. */
  522.                    }
  523.                   }
  524.  
  525.                   /* We try to restore the hardware tables now. */
  526.                   if (err) {
  527.                         props=MAPP_CACHEINHIBIT|MAPP_SINGLEPAGE;
  528.  
  529.                         if ((!SetPageProperties(ctx,props,~0L,0L,TAG_DONE)) ||
  530.                             (!SetPageProperties(sctx,props,~0L,0L,TAG_DONE))) {
  531.                                 /* We can't restore the hardware tables either! */
  532.                                 Alert(0xbe000101);
  533.                                 /* Sorry, go guru. We can't do much more here... */
  534.                         }
  535.                   }
  536.                   Enable();
  537.                  }
  538.                 }
  539.                }
  540.               }
  541.  
  542.               /* We can't build the software level. In the one way or the other,
  543.                  just restore the previous software abstraction level. */
  544.  
  545.               if (err) {
  546.                 SetPropertyList(ctx,ctxl);
  547.                 SetPropertyList(sctx,sctxl);
  548.               }
  549.  
  550.               /* The software level is now restored. The
  551.                  hardware level has been restored above.
  552.                  Now call RebuildTree() to clear the dirty
  553.                  flags.
  554.                  If this fails, tough luck. Both levels are
  555.                  actually fine, except for the busy flags. */
  556.  
  557.               RebuildTree(ctx);
  558.               RebuildTree(sctx);
  559.  
  560.               ReleaseMapping(sctx,sctxl);
  561.              }
  562.              ReleaseMapping(ctx,ctxl);
  563.             }
  564.          }
  565.  
  566.            /* Release the locks */
  567.          UnlockMMUContext(sctx);
  568.          UnlockMMUContext(ctx);
  569.          UnlockContextList();
  570.  
  571.            if (mem) FreeMem(mem,size+lower);
  572.            if (port) FreeMem(port,sizeof(struct FastZeroPort));
  573.         }
  574.  
  575.         return err;
  576. }
  577. ///
  578. /// RemoveFastZero
  579. int RemoveFastZero(void)
  580. {
  581. struct MMUContext *ctx,*sctx;
  582. struct MinList *ctxl,*sctxl;
  583. struct FastZeroPort *port;
  584. ULONG size,pagesize,lower;
  585. void *mem,*pmem;
  586. ULONG props,cacheflags;
  587. int err;
  588.  
  589.         Forbid();                               /* Shut up PatchWork */
  590.  
  591.         /* If this is not installed, warn and return. */
  592.  
  593.         port=(struct FastZeroPort *)FindPort("« MuFastZero »");
  594.  
  595.         if (port==NULL) {
  596.                 Permit();
  597.                 Printf("MuFastZero not installed.\n");
  598.                 return 5;
  599.         }
  600.         /* Remove it, to ensure nobody else tries to remove it */
  601.         RemPort(&(port->frp_Port));
  602.         Permit();
  603.  
  604.         ctx=DefaultContext();   /* get the default context */
  605.         sctx=SuperContext(ctx); /* get the supervisor context for this one */
  606.  
  607.         pagesize=GetPageSize(ctx);
  608.         if (GetPageSize(sctx)!=pagesize) {
  609.                 Printf("Supervisor and user page size are different,\n"
  610.                        "MuFastZero can't be removed.\n");
  611.                 return 10;
  612.         }
  613.  
  614.         LockContextList();      /* We've to lock the list first, we want to lock more than one */
  615.         LockMMUContext(ctx);
  616.         LockMMUContext(sctx);
  617.  
  618.         err=ERROR_NO_FREE_STORE;
  619.  
  620.         /* Make a copy of the mapping like it is now */
  621.         if (ctxl=GetMapping(ctx)) {
  622.          if (sctxl=GetMapping(sctx)) {
  623.  
  624.           /* Read the properties of the zeropage. If this is either invalid
  625.              or already remapped, don't touch. */
  626.  
  627.           lower=port->frp_Lower;
  628.           props=GetPageProperties(ctx,lower,TAG_DONE);
  629.           props|=GetPageProperties(sctx,lower,TAG_DONE);
  630.           err=0;
  631.  
  632.           if ((props & MAPP_INVALID) || (props & MAPP_SWAPPED) ||
  633.               (props & MAPP_SUPERVISORONLY)) {
  634.                 Printf("The zero page is now invalidated and can't be restored for that reason.\n");
  635.                 err=10;
  636.           }
  637.  
  638.           if ((err==0) && ((props & MAPP_REMAPPED)==0)) {
  639.                 Printf("The zero page is no longer remapped to FastMem.\n");
  640.                 err=10;
  641.           }
  642.  
  643.           /* If everything is fine so far, start removing things */
  644.           if (err==0) {
  645.            size=port->frp_Size;
  646.            pmem=port->frp_Physical;
  647.            mem=port->frp_Logical;
  648.            lower=port->frp_Lower;
  649.            cacheflags=port->frp_CacheFlags;
  650.            Disable();
  651.  
  652.            err=ERROR_NO_FREE_STORE;
  653.            props=MAPP_CACHEINHIBIT|MAPP_SINGLEPAGE;       /* This is the only flag for chip memory */
  654.  
  655.            /* Now copy the data back to the zeropage */
  656.            CopyMMULess((char *)lower,(char *)pmem+lower,size);
  657.  
  658.            /* First, try to modify the hardware tables. */
  659.            if (SetPages(ctx,props,lower,size,pagesize,lower)) {
  660.             if (SetPages(sctx,props,lower,size,pagesize,lower)) {
  661.  
  662.              /* read the data again from the real stuff */
  663.              SetMMUContextData(ctx,MCXTAG_ZEROBASE,0L,TAG_DONE);
  664.              SetMMUContextData(sctx,MCXTAG_ZEROBASE,0L,TAG_DONE);
  665.  
  666.              /* Restore the software level,singlepage is no longer required */
  667.  
  668.              props=MAPP_CACHEINHIBIT;
  669.              if (SetProperties(ctx,props,~0L,lower,size,TAG_DONE)) {
  670.               if (SetProperties(sctx,props,~0L,lower,size,TAG_DONE)) {
  671.  
  672.                         if (port->frp_LowMemHeader) {
  673.                                 /* No, neither public nor anything else */
  674.                                 port->frp_LowMemHeader->mh_Attributes=MEMF_CHIP;
  675.                         }
  676.  
  677.                         FreeMem(mem,size+lower);
  678.                         if (port->frp_Base)
  679.                                 CloseLibrary(port->frp_Base);
  680.  
  681.                         FreeMem(port,sizeof(struct FastZeroPort));
  682.                         err=0;
  683.               }
  684.              }
  685.  
  686.               /* We can't setup the software level. Urgh. At least,
  687.                  we should try to set things back how they used to be. */
  688.             }
  689.            }
  690.  
  691.  
  692.            /* We try to restore the hardware tables now. */
  693.            if (err) {
  694.                 props=MAPP_REMAPPED|MAPP_SINGLEPAGE|cacheflags;
  695.                 SetMMUContextData(ctx,MCXTAG_ZEROBASE,(ULONG)pmem+lower,TAG_DONE);
  696.                 SetMMUContextData(sctx,MCXTAG_ZEROBASE,(ULONG)pmem+lower,TAG_DONE);
  697.  
  698.                 if ((!SetPages(ctx,props,lower,size,pagesize,(ULONG)pmem+lower)) ||
  699.                     (!SetPages(sctx,props,lower,size,pagesize,(ULONG)pmem+lower))) {
  700.                         /* We can't restore the hardware tables either! */
  701.                         Alert(0xbe000101);
  702.                         /* Sorry, go guru. We can't do much more here... */
  703.                 }
  704.            }
  705.            Enable();
  706.  
  707.            if (err) {
  708.                 SetPropertyList(ctx,ctxl);
  709.                 SetPropertyList(sctx,sctxl);
  710.                 /* More luck next time */
  711.                 AddPort(&(port->frp_Port));
  712.            }
  713.  
  714.              /* The software level is now restored. The
  715.                 hardware level has been restored above.
  716.                 Now call RebuildTree() to clear the dirty
  717.                 flags.
  718.                 If this fails, tough luck. Both levels are
  719.                 actually fine, except for the busy flags. */
  720.  
  721.            RebuildTree(ctx);
  722.            RebuildTree(sctx);
  723.           }
  724.           ReleaseMapping(sctx,sctxl);
  725.          }
  726.          ReleaseMapping(ctx,ctxl);
  727.         }
  728.  
  729.  
  730.         UnlockMMUContext(sctx);
  731.         UnlockMMUContext(ctx);
  732.         UnlockContextList();      /* We've to lock the list first, we want to lock more than one */
  733.  
  734.         if (err) {
  735.                 /* Uhoh, things didn't work here... */
  736.                 Printf("Can't remove the FastZero node, sorry.\n");
  737.         }
  738.  
  739.         return err;
  740. }
  741. ///
  742. /// KillFastZero
  743. int KillFastZero(void)
  744. {
  745. struct FastZeroPort *port;
  746. struct MMUContext *ctx,*sctx;   /* default context, supervisorcontext */
  747. struct MinList *ctxl,*sctxl;    /* Copies of the mappings currently active */
  748. ULONG pagesize;
  749. ULONG lower,size,props;
  750. ULONG userpos,superpos,base;
  751. int err;
  752. BOOL retry;
  753.  
  754.  
  755.         Forbid();                               /* Shut up PatchWork */
  756.  
  757.         /* If MuFastZero is installed, remove it the easy way */
  758.  
  759.         port=(struct FastZeroPort *)FindPort("« MuFastZero »");
  760.  
  761.         if (port) {
  762.                 Permit();
  763.                 return RemoveFastZero();
  764.         }
  765.  
  766.         Permit();
  767.  
  768.         ctx=DefaultContext();   /* get the default context */
  769.         sctx=SuperContext(ctx); /* get the supervisor context for this one */
  770.  
  771.         /* Read the size */
  772.         pagesize=GetPageSize(ctx);
  773.  
  774.         if (GetPageSize(sctx)!=pagesize) {
  775.                 Printf("Supervisor and user page size are different,\n"
  776.                        "MuFastZero failed.\n");
  777.                 return 10;
  778.         }
  779.  
  780.         /* Lock the context, make sure nobody is messing with the memory */
  781.         LockContextList();      /* We've to lock the list first, we want to lock more than one */
  782.         LockMMUContext(ctx);
  783.         LockMMUContext(sctx);
  784.         err=0;
  785.  
  786.         /* Read the properties of the zeropage. If this is either invalid
  787.            or not remapped, don't touch. */
  788.  
  789.         lower=0;
  790.         size=0;
  791.         base=0;
  792.  
  793.         do {
  794.  
  795.                 retry=FALSE;
  796.                 userpos=superpos=0;
  797.                 props=GetPageProperties(ctx,lower+size,
  798.                                         MAPTAG_DESTINATION,&userpos,
  799.                                         TAG_DONE);
  800.                 props|=GetPageProperties(sctx,lower+size,
  801.                                          MAPTAG_DESTINATION,&superpos,
  802.                                          TAG_DONE);
  803.  
  804.                 if ((props & MAPP_INVALID) || (props & MAPP_SWAPPED) ||
  805.                     (props & MAPP_SUPERVISORONLY)) {
  806.  
  807.                         lower += pagesize;
  808.                         retry = TRUE;
  809.  
  810.                 } else if (props & MAPP_REMAPPED) {
  811.                         if (userpos == superpos) {
  812.  
  813.                                 if (base==0) {
  814.                                         base = userpos;
  815.                                 }
  816.                                 /* Adjacent? */
  817.                                 if (base+size == userpos) {
  818.                                         size += pagesize;
  819.                                         retry = TRUE;
  820.                                 }
  821.                         }
  822.                 }
  823.  
  824.         } while(retry);
  825.  
  826.         if (size==0L) {
  827.                 Printf("The zero page is not remapped.\n");
  828.                 err = 5;
  829.         }
  830.  
  831.          /* lower is now the lower end which is remapped.
  832.             size is the length of the remapped memory
  833.             base is the address it is remapped to */
  834.  
  835.         if (err==0L) {
  836.  
  837.          /* Make a copy of the software levels to be able to restore
  838.             them later in case of an error. */
  839.  
  840.          if (ctxl=GetMapping(ctx)) {
  841.           if (sctxl=GetMapping(sctx)) {
  842.  
  843.            /* Modify both contexts such that the zeropage is SINGLE.
  844.               This operation is very costy, but it doesn't matter
  845.               except for speed penalties if this is not un-done */
  846.  
  847.               err=ERROR_NO_FREE_STORE;
  848.               props=MAPP_SINGLEPAGE;
  849.  
  850.            if (SetProperties(ctx,props,props,lower,size,TAG_DONE)) {
  851.             if (RebuildTree(ctx)) {
  852.              if (SetProperties(sctx,props,props,lower,size,TAG_DONE)) {
  853.               if (RebuildTree(sctx)) {
  854.  
  855.                Disable();
  856.  
  857.                /* The new property flags */
  858.                props=MAPP_SINGLEPAGE|MAPP_CACHEINHIBIT;
  859.                CacheClearU();
  860.                CopyMMULess((void *)lower,(void *)base,size);
  861.  
  862.                /* Map in the properties immediately. This should always work,
  863.                   except the parameters are invalid - which they aren't.
  864.                   This extra step is required because all other calls might
  865.                   break the Disable() above. */
  866.  
  867.                if (SetPages(ctx,props,lower,size,pagesize,0L)) {
  868.                 if (SetPages(sctx,props,lower,size,pagesize,0L)) {
  869.  
  870.                  /* Tell the contexts not to relocate the zero page even in case MuForce
  871.                     is installed later, i.e. the software emulation should read
  872.                     the data from the relocated position, not from the original. */
  873.  
  874.                  SetMMUContextData(ctx,MCXTAG_ZEROBASE,0L,TAG_DONE);
  875.                  SetMMUContextData(sctx,MCXTAG_ZEROBASE,0L,TAG_DONE);
  876.  
  877.                  /* Now make the modifications in the abstraction level. */
  878.                  if (SetProperties(ctx,props,~0L,lower,size,TAG_DONE)) {
  879.                   if (SetProperties(sctx,props,~0L,lower,size,TAG_DONE)) {
  880.  
  881.                         /* The modifications in the hardware level are actually already done.
  882.                            Calling RebuildTree isn't stricly required here, but we do it
  883.                            anyways to clear the dirty flags. This might or might not fail,
  884.                            but the resulting MMU trees are always what we want. In
  885.                            case it fails, the dirty flags are set. So what... */
  886.  
  887.                         /* We're done here. Fine. */
  888.                         err=0;
  889.                   }
  890.                  }
  891.                  /* We can't set the software level. Urgh. At least, we can
  892.                     restore it how it looked like before. */
  893.                 }
  894.                } /* of if SetPages */
  895.  
  896.                /* We try to restore the hardware tables now. */
  897.                if (err) {
  898.                 props=MAPP_REMAPPED|MAPP_SINGLEPAGE|MAPP_COPYBACK;
  899.                 SetMMUContextData(ctx,MCXTAG_ZEROBASE,base,TAG_DONE);
  900.                 SetMMUContextData(sctx,MCXTAG_ZEROBASE,base,TAG_DONE);
  901.  
  902.                 if ((!SetPages(ctx,props,lower,size,pagesize,base)) ||
  903.                     (!SetPages(sctx,props,lower,size,pagesize,base))) {
  904.                         /* We can't restore the hardware tables either! */
  905.                         Alert(0xbe000101);
  906.                         /* Sorry, go guru. We can't do much more here... */
  907.                 }
  908.                }
  909.  
  910.                Enable();
  911.               }
  912.              }
  913.             }
  914.            } /* of if SetProperties() */
  915.  
  916.            /* We can't build the software level. In the one way or the other,
  917.               just restore the previous software abstraction level. */
  918.  
  919.            if (err) {
  920.                 SetPropertyList(ctx,ctxl);
  921.                 SetPropertyList(sctx,sctxl);
  922.            }
  923.  
  924.            /* The software level is now restored. The
  925.               hardware level has been restored above.
  926.               Now call RebuildTree() to clear the dirty
  927.               flags.
  928.               If this fails, tough luck. Both levels are
  929.               actually fine, except for the busy flags. */
  930.  
  931.            RebuildTree(ctx);
  932.            RebuildTree(sctx);
  933.  
  934.            ReleaseMapping(sctx,sctxl);
  935.           } /* of if made copy */
  936.           ReleaseMapping(ctx,ctxl);
  937.          } /* of if made copy */
  938.         } /* of if (err==0) */
  939.  
  940.           /* Release the locks */
  941.         UnlockMMUContext(sctx);
  942.         UnlockMMUContext(ctx);
  943.         UnlockContextList();
  944.  
  945.         return err;
  946. }
  947. ///
  948. /// ChipLowEnd
  949. ULONG ChipLowEnd(void)
  950. {
  951. ULONG low;
  952. struct MemHeader *head;
  953.  
  954.         low=0x00200000;         /* This is definitely the upper end of chip mem */
  955.  
  956.         Forbid();
  957.         for(head=(struct MemHeader *)SysBase->MemList.lh_Head;
  958.                    head->mh_Node.ln_Succ;
  959.                    head=(struct MemHeader *)(head->mh_Node.ln_Succ)) {
  960.                 if (head->mh_Attributes & MEMF_CHIP) {
  961.                         if ((ULONG)(head->mh_Lower)<low) {
  962.                                 low=(ULONG)(head->mh_Lower);
  963.                         }
  964.                 }
  965.         }
  966.         Permit();
  967.  
  968.         return low;
  969. }
  970. ///
  971. /// MoveSSP
  972. int MoveSSP(LONG stacksize)
  973. {
  974. ULONG minsize;
  975. struct Task *task;
  976. UBYTE *newstack;
  977.  
  978.         minsize=(UBYTE *)SysBase->SysStkUpper-(UBYTE *)SysBase->SysStkLower;
  979.         if (stacksize<minsize) {
  980.                 task=FindTask(NULL);
  981.                 stacksize=(UBYTE *)(task->tc_SPUpper)-(UBYTE *)(task->tc_SPLower);
  982.         }
  983.         if (stacksize<minsize)
  984.                 stacksize=minsize;
  985.  
  986.         /* Round this to two cache lines */
  987.  
  988.         stacksize += 0x1f;
  989.         stacksize &= ~0x1f;
  990.  
  991.         /* This must be fast, or this function is a joke... */
  992.         newstack=AllocMem(stacksize,MEMF_CLEAR|MEMF_PUBLIC|MEMF_FAST);
  993.  
  994.         if (newstack==NULL) {
  995.                 return ERROR_NO_FREE_STORE;
  996.         }
  997.  
  998.         SuperStackSwap(newstack,stacksize);
  999.  
  1000.         return 0;
  1001. }
  1002. ///
  1003. /// SuperStackSwap
  1004. void SuperStackSwap(UBYTE *newstack,ULONG size)
  1005. {
  1006. UBYTE *oldsp,*newsp;
  1007. size_t oldsize;
  1008. UWORD sum;
  1009. UWORD *p;
  1010.  
  1011.         /* Yup, this is possible in C */
  1012.         Disable();
  1013.         oldsp=SuperState();
  1014.  
  1015.         /* copy the stack over to the upper limit */
  1016.         oldsize=(UBYTE *)(SysBase->SysStkUpper)-oldsp;
  1017.         if (oldsize>0 && oldsize<size) {
  1018.                 newsp=newstack+size-oldsize;
  1019.                 memcpy(newsp,oldsp,oldsize);
  1020.         } else  newsp=newstack+size;
  1021.         UserState(newsp);
  1022.  
  1023.         /* Now tell this exec! */
  1024.         SysBase->SysStkUpper=newstack+size;
  1025.         SysBase->SysStkLower=newstack;
  1026.  
  1027.         /* Recalculate the checksum */
  1028.         p=&SysBase->SoftVer;
  1029.         sum=0xffff;
  1030.         while(p<&SysBase->ChkSum)
  1031.                 sum -= *p++;
  1032.  
  1033.         SysBase->ChkSum=sum;
  1034.         Enable();
  1035.  
  1036. }
  1037. ///
  1038. /// CopyMMULess
  1039. void CopyMMULess(void *to,void *from,ULONG size)
  1040. {
  1041.         _cw_from=from;
  1042.         _cw_to=to;
  1043.         _cw_size=size;
  1044.         WithoutMMU(&__CopyWO);
  1045. }
  1046. ///
  1047. /// CopyWO
  1048. ULONG __CopyWO()
  1049. {
  1050.         memcpy(_cw_to,_cw_from,(size_t)_cw_size);
  1051.         CacheClearU();
  1052.         return 0;
  1053. }
  1054. ///
  1055.  
  1056.  
  1057.  
  1058.  
  1059.